<template>
  <div class="app-container">
    <avue-crud
      ref="role_crud"
      :option="option"
      :data="data"
      :table-loading="loading"
      :page.sync="page"
      @on-load="onLoad"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @selection-change="selectionChange"
      @row-click="roleClick"
      @select="roleSelect"
      @search-change="searchChange"
      @search-reset="resetChange"
    >
      <template slot="menuLeft">
        <el-button
          type="primary"
          plain
          size="small"
          icon="el-icon-setting"
          @click="handleGrant"
        >权限设置
        </el-button>
      </template>
    </avue-crud>

    <el-dialog
      title="角色资源分配"
      class="avue-dialog"
      :visible.sync="roleBox"
      width="55%"
      @opened="roleOpen"
      center
    >
      <el-tree
        ref="author_tree"
        :indent="30"
        node-key="id"
        :check-strictly="checkStrictly"
        v-loading="loadTree"
        :expand-on-click-node="false"
        :data="list"
        :default-expanded-keys="onData"
        :props="props"
        :filter-node-method="filterNode"
        :check-on-click-node="true"
        @node-click="clickNode"
        show-checkbox
      >
      </el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="cancel">取 消</el-button>
        <el-button
          type="primary"
          @click="submit"
          :loading="isSubmit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addRole,
  upRole,
  getRole,
  delRole,
  getResTree,
  getOnRes,
  upAuthor,
} from '@/api/user.js'
export default {
  data() {
    return {
      isSubmit: false,
      loading: false,
      /* 分页 */
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        text: '',
        background: false,
      },
      data: [],
      option: {
        headerAlign: 'center',
        dialogMenuPosition:'center',
        align: 'center',
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 100,
        card: true,
        dialogDrag: false,
        selection: true,
        searchMenuSpan: 4,
        searchSpan: 6,
        searchLabelWidth: '25%',
        column: [
          {
            label: '角色名称',
            prop: 'roleName',
            search: true,
            searchPlaceholder: '请输入角色名称',
          },
          {
            label: '角色类型',
            prop: 'roleType',
            type: 'select',
            dicData: [],
          },
          /* {
                            label: '是否有效',
                            prop: 'roleIsvalid',
                            type: 'select',
                            dicData: [{
                                label: '无效',
                                value: false
                            }, {
                                label: '有效',
                                value: true
                            }]
                        },
                        {
                            label: '排序',
                            prop: 'roleOrder',
                            type: 'number',
                            value: 0,
                            width: 80,
                        }, */
          {
            label: '描述',
            prop: 'roleDesc',
            span: 24,
            type: 'textarea',
          },
          /* {
                            label: '创建时间',
                            prop: 'createTime',
                            display: false,
                            overHidden: true,
                        }, */
          /* {
                            label: "创建人",
                            prop: "cuser",
                            display: false
                        }, */
          /* {
                            label: "修改时间",
                            prop: "updateTime",
                            display: false,
                            overHidden: true,
                        }, */
          /* {
                            label: "更新人",
                            align: 'center',
                            prop: "uuser",
                            display: false
                        } */
        ],
      },

      /* 树形弹窗 */
      roleBox: false,
      selectionList: [],
      loadTree: true,
      /* tree父子关联控制 */
      checkStrictly: true,
      props: {
        label: 'resVal',
        value: 'id',
      },
      list: [],
      defaultObj: [],
      /* 已分配权限keys 用作回显 */
      onData: [],
      /* 选中的节点 */
      clickData: [],
      searchList: {},
    }
  },
  created() {
    this.$store
      .dispatch('asyncApi/getDict', {
        code: 'JSLX',
      })
      .then((res) => {
        this.option.column[1].dicData = res
      })
  },
  methods: {
    onLoad(page, params = {}) {
      /* if (page.layout) {
                    Object.assign(params, {
                        page: 1,
                        size: 10,
                    });
                } else {
                    page.roleName ? page['text'] = page.roleName : page['text'] = ''
                    Object.assign(params, page);
                } */
      let searchList = this.searchList
      Object.assign(params, {
        ...searchList,
        text: searchList.roleName,
        page: this.page.currentPage,
        size: this.page.pageSize,
      })
      this.loading = true
      getRole(params).then((data) => {
        this.loading = false
        this.data = data.data.records
        this.page.total = data.data.total
      })

      /* 渲染树形组件 */
      getResTree().then((data) => {
        if (data.status) {
          this.list = data.data.records
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    /* 清空 */
    resetChange() {
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = {}
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done()
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.searchList = {
        ...params,
      }
      this.onLoad()
    },
    /* 新增用户 */
    rowSave(row, done, loading) {
      addRole(row).then(
        (data) => {
          if (data.status) {
            done()
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            this.onLoad(this.page)
          }
        },
        (error) => {
          window.console.log(error)
          loading()
        }
      )
    },
    /* 修改用户 */
    rowUpdate(row, index, done, loading) {
      delete row.createTime
      delete row.updateTime
      upRole(row).then(
        () => {
          done()
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
        },
        (error) => {
          window.console.log(error)
          loading()
        }
      )
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delRole({
          id: row.id,
        }).then(() => {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
        })
      })
    },
    /* 角色列表行点击row选中 */
    roleClick(row) {
      this.data.map((item) => {
        if (item.id == row.id) {
          this.$refs.role_crud.toggleSelection()
          this.$refs.role_crud.toggleSelection([item])
        }
      })
    },
    /* 用户勾选复选框回调 */
    roleSelect(selection, row) {
      // this.data.map(item => {
      //     if (item.id == row.id) {
      //         this.$refs.role_crud.toggleRowSelection();
      //         this.$refs.role_crud.toggleRowSelection([item]);
      //     }
      // });
    },

    selectionChange(list) {
      this.selectionList = list
      this.loadTree = true
    },
    /* 角色配置 */
    handleGrant() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至多一条数据')
        return
      } else if (this.selectionList.length > 1) {
        this.$message.warning('请选择至多一条数据')
        return
      } else {
        this.roleBox = true
      }
    },
    roleOpen() {
      /* 渲染已分配的权限 */
      let { id } = this.selectionList[0]
      getOnRes({
        k: id,
      }).then((data) => {
        if (data.status) {
          this.onData = data.data
          let u = []
          this.onData.map((item) => {
            u.push(item)
          })
          this.$refs.author_tree.setCheckedKeys(u)
          /* 获取已选权限,展开相应节点 */
          let authors = this.$refs.author_tree.getCheckedKeys()
          // console.log(authors, 'authors')
          /* 根节点的展开 */
          this.onData = authors
          this.loadTree = false
          this.checkStrictly = true
        } else {
          this.$message.error('系统错误,请稍候再试!')
        }
      })
    },
    // 过滤权限
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexO(value) !== -1
    },
    /* 点击节点 */
    clickNode(node, check, child) {
      /* 已选择权限父节点数据集 + 已选择权限数据集 */
      let subDatas = []
      let authors = this.$refs.author_tree.getCheckedKeys()
      this.clickData = authors
    },
    submit() {
      const menuLIst = this.$refs.author_tree.getCheckedKeys()
      let { id } = this.selectionList[0]
      this.isSubmit = true
      upAuthor({
        k: id,
        v: menuLIst.toString(),
      }).then((data) => {
        if (data.status) {
          this.roleBox = false
          this.isSubmit = false
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
          this.$refs.role_crud.toggleSelection()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    cancel() {
      this.roleBox = false
      this.$refs.role_crud.toggleSelection()
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .avue-crud__pagination {
  text-align: center;
}
</style>
